import { ref, reactive, provide, unref } from "vue";
import { ElMessage } from "element-plus";
import { ColumnProps } from "../interface";

// 处理枚举数据的hook
export const useEnumMap = (columns: ColumnProps[]) => {
  // 定义 enumMap 存储 enum 值
  const enumMap = ref(new Map<string, { [key: string]: any }[]>());

  const setEnumMap = async ({ prop, enum: enumValue }: ColumnProps) => {
    if (!enumValue) return;
    // 如果当前 enumMap 存在相同的值 return
    if (enumMap.value.has(prop!) && (typeof enumValue === "function" || enumMap.value.get(prop!) === enumValue)) return;

    // 当前 enum 为静态数据，则直接存储到 enumMap
    if (typeof enumValue !== "function") return enumMap.value.set(prop!, unref(enumValue!));

    // 为了防止接口执行慢，而存储慢，导致重复请求，所以预先存储为[]，接口返回后再二次存储
    enumMap.value.set(prop!, []);

    // 当前 enum 为后台数据需要请求数据，则调用该请求接口，并存储到 enumMap
    try {
      const { data } = await enumValue();
      enumMap.value.set(prop!, data);
    } catch (error) {
      console.error(`获取枚举数据失败[${prop}]:`, error);
      ElMessage.error(`获取${prop}枚举数据失败`);
    }
  };

  // 处理所有列的枚举数据
  const handleColumnsEnum = async () => {
    for (const col of columns) {
      await setEnumMap(col);
    }
  };

  return {
    enumMap,
    setEnumMap,
    handleColumnsEnum
  };
};

// 处理分页的hook
export const usePagination = (defaultPageSize = 20) => {
  const pagination = reactive({
    pageNum: 1,
    pageSize: defaultPageSize,
    total: 0
  });

  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
  };

  const handleCurrentChange = (val: number) => {
    pagination.pageNum = val;
  };

  const resetPagination = () => {
    pagination.pageNum = 1;
    pagination.pageSize = defaultPageSize;
  };

  return {
    pagination,
    handleSizeChange,
    handleCurrentChange,
    resetPagination
  };
};

// 处理搜索参数的hook
export const useSearch = () => {
  const searchParam = ref<{ [key: string]: any }>({});
  const searchInitParam = ref<{ [key: string]: any }>({});

  // 设置搜索参数的默认值
  const setSearchInitParam = (columns: ColumnProps[]) => {
    columns.forEach(column => {
      const key = column.search?.key ?? column.prop;
      const defaultValue = column.search?.defaultValue;
      if (defaultValue !== undefined && defaultValue !== null) {
        searchInitParam.value[key!] = defaultValue;
        searchParam.value[key!] = defaultValue;
      }
    });
  };

  // 重置搜索参数
  const resetSearchParam = () => {
    searchParam.value = { ...searchInitParam.value };
  };

  return {
    searchParam,
    searchInitParam,
    setSearchInitParam,
    resetSearchParam
  };
};

// 提供enumMap的函数（需要在组件setup中调用）
export const provideEnumMap = (enumMap: any) => {
  provide("enumMap", enumMap);
};
